package com.minelx.statementsplus;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.minelx.sequence.common.Templates;
import com.minelx.util.Files;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;

public class MajorSqlHeadFactory {
	public static final String SQL_CONTENT = "sqlContent";

	public static final String LOOP_ID = "loopId";

	public static final String MAPPING_KEYS = "mapping_keys";

	private final JSONObject data;

	public MajorSqlHeadFactory(JSONObject data) {
		this.data = data;
	}

	public MajorSqlHead createMajorSqlHead(String name, Map<String, String> parameters) {
		JSONObject majorSqlAsJSON = data.getJSONObject(name);
		String content = majorSqlAsJSON.getString(SQL_CONTENT);
		return new MajorSqlHead(new Templates(content).render(parameters),
				majorSqlAsJSON.getString(LOOP_ID),
				majorSqlAsJSON.getJSONArray(MAPPING_KEYS).toJavaList(String.class));
	}

	public static MajorSqlHeadFactory general() {
		String content = Files.toString(Objects.requireNonNull(MajorSqlHeadFactory.class.getResourceAsStream("/major_sql_head.json")), StandardCharsets.UTF_8);
		return new MajorSqlHeadFactory(JSON.parseObject(content));
	}
}